package com.maxjay.system.web.controller;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.maxjay.system.constant.YesNoConstant;
import com.maxjay.system.po.BaseEntity;
import com.maxjay.system.po.TSysUser;
import com.maxjay.system.service.BaseService;
import com.maxjay.system.service.UserService;

@Controller
@RequestMapping("/sys/user.do")
public class UserController extends BaseMultiActionController {
	
	@Resource
	UserService userService;
	
	@Resource(name = "baseService")
	private BaseService baseService;
	
	@RequestMapping(params="method=show")
	public String show(String userId, ModelMap modelMap) {
		TSysUser sysUser = userService.getUser(userId);
		modelMap.addAttribute("user", sysUser);
		return "user/showUser";
	}
	
	@RequestMapping(params="method=add")
	public String add() {
		return "user/add";
	}

	@RequestMapping(params="method=save")
	public String save(TSysUser user, ModelMap modelMap) {
		String errorMsg = "";
		if(userService.validateUserExist(user.getLoginId())){
			errorMsg = "该登录名已经存在，请使用其他名字登录";
			modelMap.addAttribute("user", user);
			modelMap.addAttribute("errorMsg", errorMsg);
			return "user/add";
		}
		user.setIsManager(YesNoConstant.NO);
		saveOrValidateUpdate(user);
		return "familyUserList";
	}

	@RequestMapping(params="method=edit", method=RequestMethod.GET)
	public String edit(String userId, ModelMap modelMap) {
		TSysUser user = userService.getUser(userId);
		modelMap.addAttribute("user", user);
		return "user/edit";
	}

	@RequestMapping(params="method=update", method=RequestMethod.POST)
	public String update(TSysUser user){
		saveOrValidateUpdate(user);
		return "familyUserList";
	}
	
	protected void saveOrValidateUpdate(BaseEntity baseEntityVo) {
		if(StringUtils.isNotBlank(baseEntityVo.getObjId())){
			validateUpdate(baseEntityVo);
		} else {
			getBaseService().save(baseEntityVo);
		}
	}
	
	private void validateUpdate(BaseEntity baseEntityVo){
//		getBaseService().validateUpdate(baseEntityVo, updateKey);
	}
	
	protected BaseService getBaseService(){
		return baseService;
	}
}
